package com.yangchoi.jetpackcompose

import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import com.yangchoi.lib_base.base.BaseViewModel
import dagger.hilt.android.lifecycle.HiltViewModel
import javax.inject.Inject
import javax.inject.Singleton

/**
 * 全局管理viewModel
 *
 * 记录一些全局数据，比如登录状态啥的
 *
 * 使用步骤:
 * 1. 先搞一个顶层声明,方便在任意地方调用 val LocalGlobalViewModel = staticCompositionLocalOf<GlobalViewModel> { error("No GlobalViewModel provided") }
 * 2. 使用viewmodel private val globalViewModel: GlobalViewModel by viewModels()
 * 3. 将viewModel传入最根部的布局  MainScaffoldConfig(globalViewModel)
 * 4. 在最根部的布局实现provides
 *    CompositionLocalProvider(LocalGlobalViewModel provides globalViewModel) {
 *      // todo ...这里放布局
 *    }
 * 5. 在需要使用到的地方获取global持有对象 val globalCurrent = LocalGlobalViewModel.current
 * 6. 然后通过持有对象去操作viewModel的内容 globalCurrent.globalState.isUserLogin || globalCurrent.dispatch(event = GlobalEvent.OnSetLoginState, isLogin = true)
 */
@Singleton
//@HiltViewModel
class GlobalViewModel @Inject constructor() : BaseViewModel() {
    var globalState by mutableStateOf(GlobalState())
        set

    fun dispatch(event: GlobalEvent, isLogin:Boolean = false,positionIndex:Int = -1){
        when(event){
            GlobalEvent.OnSetLoginState -> {
                globalState = globalState.copy(isUserLogin = isLogin)
                if (positionIndex != -1){
                    globalState = globalState.copy(bottomIndex = positionIndex)
                }
            }
            GlobalEvent.OnUpdateBottomIndex ->{
                if (positionIndex != -1){
                    globalState = globalState.copy(bottomIndex = positionIndex)
                }
            }
        }
    }
}

data class GlobalState(
    var bottomIndex: Int = 0, // todo 底部按钮
    var isUserLogin: Boolean = false, // todo 是否登录
)

sealed class GlobalEvent{
    object OnSetLoginState : GlobalEvent()
    object OnUpdateBottomIndex : GlobalEvent()
}